package day11.test3;

class Plate {
    private int num;//桃子的数量
    private final Object lock = new Object();//锁对象
    private boolean isEmpty;//true为空 false为满
    private int i = 0;//设置线程交互循环的次数

    public Plate() {
        this.num = 0;//一开始为空，需要服务员上桃子
        this.isEmpty = true;
    }

    public void serving() throws InterruptedException {
        synchronized (lock) {
            while (isEmpty == false) {//没有空就wait()
                lock.wait();//释放锁并且开始等待
            }
            System.out.println("服务员正在上桃子。");
            Thread.sleep(500);
            this.num = 5;
            isEmpty = false;
            System.out.println("桃子上满了，大家尽情享用吧");
            lock.notify();
        }
    }

    public void Guest_Eating() throws InterruptedException {
        synchronized (lock) {
            while (isEmpty == true) {
                System.out.println("盘子里面的桃子空了，通知服务员上桃子");
                lock.wait();
            }
            System.out.println("客人正在吃桃子");
            Thread.sleep(500);
            while (this.num != 0) {
                this.num--;
                System.out.println("还有" + this.num + "个桃子");
                Thread.sleep(500);
            }
            i++;
            if (i == 2) {
                System.exit(0);
            }
            this.isEmpty = true;
            lock.notify();
        }
    }
}

public class run {
    public static void main(String[] args) throws InterruptedException {
        Plate plate = new Plate();
        Thread thread1 = new Thread(() -> {
            while (true) {
                try {
                    plate.serving();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            while (true) {
                try {
                    plate.Guest_Eating();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread1.start();
        Thread.sleep(1000);
        thread2.start();
        Thread.sleep(1000);
    }
}
